import Vue from 'vue'
import { login, oauth2Login, logout, phoneLogin, thirdLogin, dingtalkLogin, codeLogin } from "@/api/login"
import { USER_INFO,USER_AUTH,SYS_BUTTON_AUTH } from "@/store/mutation-types"
import { queryPermissionsByUser } from '@/api/api'
import { getAction,queryTopMenuList } from '@/api/manage'
import YchConstant from "@/api/YchConstant";
import {SSO} from "../../sso/SSO";
import TokenStorageUtil from "../../utils/TokenStorageUtil";

const user = {
  state: {
    CONSOLE_INDEX_MAIN_PAGE_PATH:  "/app/group",
    CONSOLE_INDEX_MAIN_PAGE_NAME:  "app-group",
    token: '',
    permissionList: [],
    newMenuData:[],
    modulemenuList:[],//十大功能子路由
    currentModulemenuObj:{},//记录当前点击的功能
    info: {},
    rewriteGlobalTabs:false,//是否写全局页签，添加当前功能的工作台为第一个
    onlyCurrentPath:'',//只有一个功能的时候
    switchDepartments:false,//切换部门
    currentRouterPath:'',
  },

  mutations: {
    SET_TOKEN: (state, token) => {
      state.token = token
      if(token){
        TokenStorageUtil.set(token)
      } else {
        TokenStorageUtil.remove()
      }
    },
    SET_NEWMENUDATA: (state, newMenuData) => {
      state.newMenuData = newMenuData
    },
    SET_PERMISSIONLIST: (state, permissionList) => {
      state.permissionList = permissionList
    },
    SET_ONLYCURRENTPATH: (state, onlyCurrentPath) => {
      state.onlyCurrentPath = onlyCurrentPath
    },
    SET_CURRENTROUTERPATH:(state, currentRouterPath)=>{
      state.currentRouterPath = currentRouterPath
    },
    SET_MODULEMENULIST: (state, modulemenuList) => {
      state.modulemenuList = modulemenuList
    },
    SET_SWITCHDEPARTMENTS: (state, switchDepartments) => {
      state.switchDepartments = switchDepartments
    },
    SET_CURRENTMODULEMENUOBJ: (state, currentModulemenuObj) => {
      state.currentModulemenuObj = currentModulemenuObj
    },
    SET_REWRITEGLOBALTABS: (state, rewriteGlobalTabs) => {
      //console.log('不需要清空路由吗？',rewriteGlobalTabs)
      state.rewriteGlobalTabs = rewriteGlobalTabs
    },
    SET_INFO: (state, info) => {
      state.info = info || {}
      Vue.ls.set(USER_INFO, info || {}, 7 * 24 * 60 * 60 * 1000)
    },
    setConsoleIndex(state, index) {
      if (index?.path && index?.name) {
        state.CONSOLE_INDEX_MAIN_PAGE_PATH = index.path
        state.CONSOLE_INDEX_MAIN_PAGE_NAME = index.name
      }
    }
  },

  actions: {
    // CAS验证登录
    ValidateLogin({ commit }, userInfo) {
      return new Promise((resolve, reject) => {
        getAction(YchConstant.PREFIX_SYSTEM + "/cas/client/validateLogin",userInfo).then(response => {
          //console.log("----cas 登录--------",response);
          if(response.success){
            const result = response.result
            const userInfo = result.userInfo
            commit('SET_TOKEN', result.token)
            commit('SET_INFO', userInfo)
            resolve(response)
          }else{
            resolve(response)
          }
        }).catch(error => {
          reject(error)
        })
      })
    },
    // 登录
    Login({ commit }, userInfo) {
      return new Promise((resolve, reject) => {
        login(userInfo).then(response => {
          if(response.code =='200'){
            const result = response.result
            const userInfo = result.userInfo
            commit('SET_TOKEN', result.token)
            commit('SET_INFO', userInfo)
            resolve(response)
            //console.log('登录成功')
          }else{
            reject(response)
          }
        }).catch(error => {
          reject(error)
        })
      })
    },
    CodeLogin({commit}, userInfo){
      return new Promise((resolve, reject) => {
        codeLogin(userInfo).then(response => {
          if(response.code =='200'){
            const result = response.result
            const userInfo = result.userInfo
            commit('SET_TOKEN', result.token)
            commit('SET_INFO', userInfo)
            resolve(response)
            //console.log('登录成功')
          }else{
            reject(response)
          }
        }).catch(error => {
          reject(error)
        })
      })
    },
    Oauth2Login({commit}, parameter) {
      return new Promise((resolve, reject) => {
        oauth2Login(parameter).then(response => {
          if (response.code == '200') {
            const result = response.result
            const userInfo = result.userInfo
            commit('SET_TOKEN', result.token)
            commit('SET_INFO', userInfo)
            resolve(response)
          } else {
            reject(response)
          }
        }).catch(error => {
          reject(error)
        })
      })
    },
    DingtalkLogin({commit}, parameter) {
      return new Promise((resolve, reject) => {
        dingtalkLogin(parameter).then(response => {
          if (response.code == '200') {
            const result = response.result
            const userInfo = result.userInfo
            commit('SET_TOKEN', result.token)
            commit('SET_INFO', userInfo)
            resolve(response)
          } else {
            reject(response)
          }
        }).catch(error => {
          reject(error)
        })
      })
    },
    //手机号登录
    PhoneLogin({ commit }, userInfo) {
      return new Promise((resolve, reject) => {
          phoneLogin(userInfo).then(response => {
          if(response.code =='200'){
        const result = response.result
        const userInfo = result.userInfo
        commit('SET_TOKEN', result.token)
        commit('SET_INFO', userInfo)
        resolve(response)
      }else{
        reject(response)
      }
    }).catch(error => {
        reject(error)
      })
    })
    },
    // 获取用户信息
    GetPermissionList({ commit }) {
      return new Promise((resolve, reject) => {
        let v_token = TokenStorageUtil.get();
        let params = {token:v_token};
        
        queryPermissionsByUser(params).then(response => {
          const menuData = response.result.menu;
          const authData = response.result.auth;
          const allAuthData = response.result.allAuth;
          //Vue.ls.set(USER_AUTH,authData);
          sessionStorage.setItem(USER_AUTH,JSON.stringify(authData));
          sessionStorage.setItem(SYS_BUTTON_AUTH,JSON.stringify(allAuthData));
          if (menuData && menuData.length > 0) {
            menuData.forEach((item, index) => {
              if (item["children"]) {
                let hasChildrenMenu = item["children"].filter((i) => {
                  return !i.hidden || i.hidden == false
                })
                if (hasChildrenMenu == null || hasChildrenMenu.length == 0) {
                  item["hidden"] = true
                }
              }
            })
            commit('SET_PERMISSIONLIST', menuData)
          } else {
            reject('getPermissionList: permissions must be a non-null array !')
          }
          resolve(response)
        }).catch(error => {
          reject(error)
        })
        //在这里写生成水印--考虑到还有单点登录的原因
      })
    },
    //新菜单
    getNewMenuData({ commit }){
      return new Promise((resolve, reject) => {
        queryTopMenuList().then(res=>{
            commit('SET_NEWMENUDATA', res.result && res.result.length?res.result:[])
            resolve(res.result)
        })
      })
    },
    getCurrentModulemenuObj({ commit,state }, data) {
      return new Promise((resolve, reject) => {
        // sessionStorage.setItem('',JSON.stringify(authData));
        let item = {}
        
        if(data){
          item = data
        }else{
          item = sessionStorage.getItem('currentModulemenuObj')?JSON.parse(sessionStorage.getItem('currentModulemenuObj')):{}
        }
        if(item.path){
          state.permissionList.forEach((trem,index)=>{
            if(trem.meta.title == item.name && trem.path == item.path){
              sessionStorage.setItem('currentModulemenuObj', JSON.stringify({...item,componentProps:[],children:[],childrenFirstPath:trem.children[0].path,childrenName:trem.children[0].name,childrenTitle:trem.children[0].meta.title}))
              commit('SET_MODULEMENULIST', trem.children && trem.children.length?trem.children:[])
              commit('SET_CURRENTMODULEMENUOBJ', {...item,childrenTitle:trem.children[0].meta.title})
            }
          })
        }
        // commit('SET_PERMISSIONLIST', menuData)
        //console.log('我这是得到了什么呢？缓存中',sessionStorage.getItem('currentModulemenuObj'))
        //console.log('路由 ----全部',state.permissionList)
        //console.log('路由 ----全部1',item)
        resolve(item)
      })
    },

    // 登出
    Logout({ commit, state }, parameter) {
      const oss = parameter && parameter.oss;
      return new Promise((resolve) => {
        let logoutToken = state.token;
        commit('SET_TOKEN', '')
        commit('SET_PERMISSIONLIST', [])
        logout(logoutToken).then(() => {
          //console.log('退出登录')
          // 手动退出与自动退出都走这里，只有手动退出需要同步退出单点
          if (bootConfig[process.env.NODE_ENV].VUE_APP_SSO === "cas" && oss) {
            // cas通过前台退出
            let sevice = window.location.protocol + '//' + window.location.host + process.env.BASE_URL;
            let serviceUrl = encodeURIComponent(sevice);
            window.location.href = bootConfig[process.env.NODE_ENV].VUE_APP_CAS_URL + "/logout?service=" + serviceUrl;
            return;
          } else if (bootConfig[process.env.NODE_ENV].VUE_APP_SSO === "oauth2" && oss) {
            // oauth2通过前台退出
            SSO.logoutByOauth2();
            return;
          }
          resolve()
        }).catch(() => {
          resolve()
        })
      })
    },
    // 第三方登录
    ThirdLogin({ commit }, token) {
      return new Promise((resolve, reject) => {
        thirdLogin(token).then(response => {
          if(response.code =='200'){
            const result = response.result
            const userInfo = result.userInfo
            commit('SET_TOKEN', result.token)
            commit('SET_INFO', userInfo)
            resolve(response)
          }else{
            reject(response)
          }
        }).catch(error => {
          reject(error)
        })
      })
    },

  }
}

export default user
